<template>
    <!-- 对话框表单 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="60%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate === 'Add' ? '添加升级条件' : baTable.form.operate === 'Edit' ? '编辑升级条件' : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <!-- 用户选择 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <FormItem 
                                label="用户" 
                                type="remoteSelect" 
                                v-model="baTable.form.items!.user_id" 
                                prop="user_id" 
                                :input-attr="{ 
                                    pk: 'id', 
                                    field: 'nickname', 
                                    'remote-url': '/admin/user.User/index',
                                    placeholder: '请选择用户',
                                    clearable: true
                                }" 
                                :placeholder="t('Please select field', { field: '用户' })" 
                            />
                        </el-col>
                        <el-col :span="12">
                            <FormItem 
                                label="条件类型" 
                                type="select" 
                                v-model="baTable.form.items!.condition_type" 
                                prop="condition_type"
                                :data="conditionTypeOptions"
                                :placeholder="t('Please select field', { field: '条件类型' })" 
                            />
                        </el-col>
                    </el-row>

                    <!-- 目标设置 -->
                    <el-row :gutter="20">
                        <el-col :span="12" v-if="baTable.form.items!.condition_type == 1">
                            <FormItem 
                                label="目标用户" 
                                type="remoteSelect" 
                                v-model="baTable.form.items!.target_user_id" 
                                prop="target_user_id" 
                                :input-attr="{ 
                                    pk: 'id', 
                                    field: 'nickname', 
                                    'remote-url': '/admin/user.User/index',
                                    placeholder: '请选择目标用户',
                                    clearable: true
                                }" 
                                :placeholder="t('Please select field', { field: '目标用户' })" 
                            />
                        </el-col>
                        <el-col :span="12">
                            <FormItem 
                                label="目标数量" 
                                type="number" 
                                prop="target_count" 
                                :input-attr="{ 
                                    step: 1, 
                                    min: 1,
                                    placeholder: '请输入目标数量'
                                }" 
                                v-model.number="baTable.form.items!.target_count" 
                                :placeholder="t('Please input field', { field: '目标数量' })" 
                            />
                        </el-col>
                    </el-row>

                    <!-- 进度信息 -->
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <FormItem 
                                label="当前进度" 
                                type="number" 
                                prop="current_count" 
                                :input-attr="{ 
                                    step: 1, 
                                    min: 0,
                                    placeholder: '当前完成数量'
                                }" 
                                v-model.number="baTable.form.items!.current_count" 
                                :placeholder="t('Please input field', { field: '当前进度' })" 
                            />
                        </el-col>
                        <el-col :span="8">
                            <FormItem 
                                label="完成状态" 
                                type="radio" 
                                v-model="baTable.form.items!.is_completed" 
                                prop="is_completed" 
                                :data="completionOptions"
                                :placeholder="t('Please select field', { field: '完成状态' })" 
                            />
                        </el-col>
                        <el-col :span="8">
                            <div class="progress-summary">
                                <div class="progress-item">
                                    <span class="label">完成进度：</span>
                                    <span class="value">{{ progressPercentage }}%</span>
                                </div>
                                <div class="progress-item">
                                    <span class="label">剩余数量：</span>
                                    <span class="value remaining">{{ remainingCount }}</span>
                                </div>
                            </div>
                        </el-col>
                    </el-row>

                    <!-- 提示信息 -->
                    <el-alert
                        v-if="baTable.form.operate === 'Add'"
                        title="添加升级条件说明"
                        type="info"
                        :closable="false"
                        show-icon
                        style="margin-bottom: 20px;"
                    >
                        <template #default>
                            <div>
                                <p>• 用户：需要升级的用户</p>
                                <p>• 条件类型：1=订单支付条件，2=邀请人数条件</p>
                                <p>• 目标用户：订单支付条件时需要指定目标用户</p>
                                <p>• 目标数量：需要完成的目标数量</p>
                                <p>• 当前进度：已经完成的数量</p>
                                <p>• 完成状态：是否已完成该条件</p>
                            </div>
                        </template>
                    </el-alert>

                    <!-- 用户信息预览 -->
                    <div v-if="selectedUserInfo || selectedTargetUserInfo" class="user-preview">
                        <el-row :gutter="20">
                            <el-col :span="12" v-if="selectedUserInfo">
                                <el-card shadow="never" style="margin-bottom: 20px;">
                                    <template #header>
                                        <div class="card-header">
                                            <span>用户信息</span>
                                        </div>
                                    </template>
                                    <div class="user-info">
                                        <el-avatar :size="48" :src="selectedUserInfo.avatar || '/static/images/avatar.png'" />
                                        <div class="user-details">
                                            <h4>{{ selectedUserInfo.nickname || selectedUserInfo.username }}</h4>
                                            <p>手机号：{{ selectedUserInfo.mobile || '未设置' }}</p>
                                            <p>当前等级：{{ selectedUserInfo.level === 2 ? '店长' : '普通用户' }}</p>
                                        </div>
                                    </div>
                                </el-card>
                            </el-col>
                            <el-col :span="12" v-if="selectedTargetUserInfo">
                                <el-card shadow="never" style="margin-bottom: 20px;">
                                    <template #header>
                                        <div class="card-header">
                                            <span>目标用户信息</span>
                                        </div>
                                    </template>
                                    <div class="user-info">
                                        <el-avatar :size="48" :src="selectedTargetUserInfo.avatar || '/static/images/avatar.png'" />
                                        <div class="user-details">
                                            <h4>{{ selectedTargetUserInfo.nickname || selectedTargetUserInfo.username }}</h4>
                                            <p>手机号：{{ selectedTargetUserInfo.mobile || '未设置' }}</p>
                                            <p>当前等级：{{ selectedTargetUserInfo.level === 2 ? '店长' : '普通用户' }}</p>
                                        </div>
                                    </div>
                                </el-card>
                            </el-col>
                        </el-row>
                    </div>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, reactive, ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const selectedUserInfo = ref(null)
const selectedTargetUserInfo = ref(null)

const { t } = useI18n()

// 条件类型选项
const conditionTypeOptions = {
    content: {
        '1': '订单支付',
        '2': '邀请人数'
    }
}

// 完成状态选项
const completionOptions = {
    content: {
        '1': '已完成',
        '0': '未完成'
    }
}

// 计算完成进度百分比
const progressPercentage = computed(() => {
    const current = baTable.form.items?.current_count || 0
    const target = baTable.form.items?.target_count || 1
    return Math.min(Math.round((current / target) * 100), 100)
})

// 计算剩余数量
const remainingCount = computed(() => {
    const current = baTable.form.items?.current_count || 0
    const target = baTable.form.items?.target_count || 1
    return Math.max(target - current, 0)
})

// 表单验证规则
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    user_id: [
        buildValidatorData({ name: 'required', title: '用户' })
    ],
    condition_type: [
        buildValidatorData({ name: 'required', title: '条件类型' })
    ],
    target_count: [
        buildValidatorData({ name: 'required', title: '目标数量' }),
        buildValidatorData({ name: 'number', title: '目标数量' })
    ],
    current_count: [
        buildValidatorData({ name: 'number', title: '当前进度' })
    ],
    is_completed: [
        buildValidatorData({ name: 'required', title: '完成状态' })
    ]
})

// 监听用户选择变化
watch(() => baTable.form.items?.user_id, async (newUserId) => {
    if (newUserId) {
        await loadUserInfo(newUserId, 'user')
    } else {
        selectedUserInfo.value = null
    }
})

// 监听目标用户选择变化
watch(() => baTable.form.items?.target_user_id, async (newUserId) => {
    if (newUserId) {
        await loadUserInfo(newUserId, 'targetUser')
    } else {
        selectedTargetUserInfo.value = null
    }
})

// 加载用户信息
const loadUserInfo = async (userId: number, type: 'user' | 'targetUser') => {
    try {
        // 这里应该调用API获取用户详细信息
        // const response = await fetch(`/admin/user.User/read/${userId}`)
        // const userData = response.data
        
        // 临时数据
        const userData = {
            id: userId,
            nickname: '用户' + userId,
            username: 'user' + userId,
            mobile: '138****' + userId.toString().padStart(4, '0'),
            avatar: '/static/images/avatar.png',
            level: Math.random() > 0.5 ? 2 : 1
        }

        if (type === 'user') {
            selectedUserInfo.value = userData
        } else {
            selectedTargetUserInfo.value = userData
        }
    } catch (error) {
        console.error('加载用户信息失败:', error)
    }
}
</script>

<style scoped lang="scss">
.progress-summary {
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    .progress-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        &:last-child {
            margin-bottom: 0;
        }
        
        .label {
            font-size: 14px;
            color: #606266;
        }
        
        .value {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
            
            &.remaining {
                color: #e6a23c;
            }
        }
    }
}

.user-preview {
    .user-info {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        
        .user-details {
            flex: 1;
            
            h4 {
                margin: 0 0 8px 0;
                color: #303133;
                font-size: 16px;
            }
            
            p {
                margin: 4px 0;
                color: #606266;
                font-size: 14px;
            }
        }
    }
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    span {
        font-weight: bold;
        color: #303133;
    }
}
</style>
